#!/bin/bash
# *******************************************
# * 功能: Shell 实现 Ubuntu LNMP环境部署脚本
# * 作者: 王树森
# * 联系: wangshusen@sswang.com
# * 版本: 2025-06-02
# *******************************************


# 配置 dpkg 自动处理配置文件冲突
echo 'Dpkg::Options {
    "--force-confdef";
    "--force-confold";
};' > /etc/apt/apt.conf.d/02dpkg-conf
dpkg --configure -a

# 定义函数：获取第一个以 "ens" 开头的网卡IP地址
get_first_ens_ip() {
    local iface_name=$(ip -o link show | awk -F': ' '{print $2}' | grep '^ens' | head -n 1)
    local ip_address=$(ip addr show "$iface_name" | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | head -n 1)
    echo "${ip_address}"
}

# 获取服务器IP地址
SERVER_IP=$(get_first_ens_ip)
if [ -z "$SERVER_IP" ]; then
    SERVER_IP=$(hostname -I | awk '{print $1}')
fi

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # 重置颜色

# 格式化输出函数
print_title() {
    echo -e "\n${BLUE}============================================${NC}"
    echo -e "${BLUE}| $1${NC}"
    echo -e "${BLUE}============================================${NC}"
}

print_info() {
    echo -e "${YELLOW}[*] $1${NC}"
}

print_success() {
    echo -e "${GREEN}[✓] $1${NC}"
}

print_error() {
    echo -e "${RED}[✗] $1${NC}"
}

# 检查是否为root用户
check_root() {
    if [ "$(id -u)" != "0" ]; then
        print_error "错误：必须使用root用户运行此脚本！"
        exit 1
    fi
}

# 更新系统
update_system() {
    print_title "更新系统软件包"
    print_info "正在更新系统软件包..."
    apt update -y
    print_success "系统更新完成！"
}

# 安装依赖工具
install_dependencies() {
    print_title "安装基础依赖工具"
    print_info "安装 wget curl gnupg2 software-properties-common..."
    apt install -y wget curl gnupg2 software-properties-common
    print_success "依赖工具安装完成！"
}

# 安装Nginx
install_nginx() {
    print_title "安装Nginx"
    print_info "开始安装Nginx..."
    apt install -y nginx
    
    # 启动并设置开机自启
    systemctl start nginx
    systemctl enable nginx
    
    # 检查Nginx状态
    if systemctl is-active --quiet nginx; then
        print_success "Nginx 已启动，状态正常！"
    else
        print_error "Nginx 启动失败，请检查日志：systemctl status nginx"
    fi
}

# 安装MySQL
install_mysql() {
    print_title "安装MySQL"
    print_info "开始安装MySQL Server..."
    apt install -y mysql-server
    
    # 启动并设置开机自启
    systemctl start mysql
    systemctl enable mysql
    
    # 安全配置
    MYSQL_ROOT_PASSWORD="LNMP@2025"
    mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$MYSQL_ROOT_PASSWORD';"
    mysql -e "FLUSH PRIVILEGES;"
    
    print_success "MySQL 安全配置完成："
    print_info "  - root@localhost 密码：$MYSQL_ROOT_PASSWORD"
    print_info "  - 已禁用匿名用户/测试数据库等（默认配置）"
}

# 安装PHP
install_php() {
    print_title "安装PHP"
    print_info "开始安装PHP及常用模块..."
    apt install -y php-fpm php-mysql php-cli php-curl php-gd php-mbstring php-xml php-zip php-bcmath php-intl
    
    # 检查PHP版本
    PHP_VERSION=$(php -v | head -n 1 | cut -d ' ' -f 2)
    print_success "PHP $PHP_VERSION 安装完成，已安装模块："
    php -m | grep -E "mysql|curl|gd|mbstring|xml|zip"
}

# 配置Nginx支持PHP
configure_nginx_php() {
    print_title "配置Nginx解析PHP"
    print_info "创建Nginx配置文件..."
    
    cat > /etc/nginx/sites-available/default <<EOF
server {
    listen 80;
    server_name localhost;
    root /var/www/html;
    index index.php index.html index.htm;

    location / {
        try_files \$uri \$uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php-fpm.sock;
    }

    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
    }
}
EOF

    # 重启Nginx使配置生效
    systemctl restart nginx
    if systemctl is-active --quiet nginx; then
        print_success "Nginx 配置更新完成，服务已重启！"
    else
        print_error "Nginx 重启失败，请检查配置文件：/etc/nginx/sites-available/default"
    fi
}

# 创建PHP测试文件
create_test_file() {
    print_title "创建PHP测试文件"
    print_info "创建phpinfo.php文件..."
    echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php
    
    # 检查文件
    if [ -f /var/www/html/phpinfo.php ]; then
        print_success "测试文件已创建：http://$SERVER_IP/phpinfo.php"
        print_info "访问上述地址，若显示PHP信息则环境正常！"
    fi
}

# 清理缓存
cleanup() {
    print_title "清理系统"
    print_info "清理系统缓存..."
    apt clean
    print_success "系统缓存清理完成！"
}

# 显示部署结果
show_summary() {
    print_title "部署完成"
    echo -e "${GREEN}============================================${NC}"
    echo -e "${GREEN}|         LNMP环境部署成功！               |${NC}"
    echo -e "${GREEN}============================================${NC}"
    echo -e "${YELLOW}服务器IP: $SERVER_IP${NC}"
    echo -e "${YELLOW}1. 访问 http://$SERVER_IP 可看到Nginx默认页${NC}"
    echo -e "${YELLOW}2. 访问 http://$SERVER_IP/phpinfo.php 可看到PHP信息${NC}"
    echo -e "${YELLOW}3. MySQL root密码：LNMP@2025（请及时修改）${NC}"
    echo -e "${YELLOW}4. 后续可通过编辑 /etc/nginx/sites-available/default 配置站点${NC}"
    echo -e "${GREEN}============================================${NC}"
}

# 主函数
main() {
    check_root
    update_system
    install_dependencies
    install_nginx
    install_mysql
    install_php
    configure_nginx_php
    create_test_file
    cleanup
    show_summary
}

# 执行主函数
main

